const path = require('path')
const fs = require('fs-extra')
const util = require('util')
const file = require('./supportedFileExtensions')
const folder = require('./supportedFolders')
const svgson = require('svgson')

const map = new Map()

async function read(iconPath) {
    if (map.has(iconPath)) {
        return map.get(iconPath)
    }
    const svgText = await fs.readFile(iconPath, {
        encoding: 'utf-8'
    })
    map.set(iconPath, svgText)
    return svgText
}

module.exports = function (name, isFile, isSymbol) {
    let id
    let rootPath
    let x
    let y
    if (isFile) {
        id = file(name).icon
        rootPath = path.join(__dirname, 'file')
        x = 2
        y = 18
    } else {
        id = folder(name).icon
        rootPath = path.join(__dirname, 'folder')
        x = 2
        y = 14
    }
    let uniqueId = id
    if (isSymbol) {
        uniqueId += '_shortcut'
    }
    return {
        id: uniqueId,
        read: async function (iconName) {
            const iconPath = path.join(rootPath, id, iconName)
            const text = await read(iconPath)
            const node = await svgson.parse(text)
            const viewBox = node.attributes.viewBox.split(' ')
            const vw = parseInt(viewBox[2])
            const vh = parseInt(viewBox[3])
            node.name = 'symbol'
            if (isSymbol) {
                const insetPath = path.join(__dirname, 'inset', 'shortcut.svg')
                const insetText = await read(insetPath)
                const insetNode = await svgson.parse(insetText)
                x = (x / 32) * vw
                y = (y / 32) * vh
                insetNode.attributes.height = (14 / 32) * vw
                insetNode.attributes.width = (14 / 32) * vh
                const group = {
                    name: 'g',
                    type: 'element',
                    value: '',
                    parent: null,
                    attributes: {
                        transform: util.format('translate(%s, %s)', x, y)
                    },
                    children: [insetNode]
                }
                node.children.push(group)
            }
            node.attributes.id = uniqueId
            return {
                id: uniqueId,
                size: {
                    width: vw,
                    height: vh
                },
                symbol: svgson.stringify(node)
            }
        }
    }
}
